﻿using CardMonitor.Model;
using CardMonitor.Utils;
using CardMonitor.ViewModel;
using CardMonitor.Windows;
using DotNetSpeech;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace CardMonitor.Pages
{
    /// <summary>
    /// Cards.xaml 的交互逻辑
    /// </summary>
    public partial class Cards : Page
    {
        public Cards()
        {
            InitializeComponent();
            billModel = new BillModel();
            viewModel = new IndexViewModel();
            viewModel.index = 0;
            _syncContext = SynchronizationContext.Current;






            this.DataContext = billModel;
            mainWindow = (MainWindow)Window.GetWindow(this);

            this.Loaded += MMPage_Loaded;

            callbackAction += CallBackExcute;

        }




        /// <summary>
        /// Card.xaml 的交互逻辑
        /// </summary>

        BillModel billModel = null;
            private PortControlHelper pchSend;
            private PortControlHelper portWrite;
            private String curInputTag = "mobile";
            private SolidColorBrush activeBrush = new SolidColorBrush(Color.FromRgb(186, 234, 255));
            MainWindow mainWindow = null;
            SynchronizationContext _syncContext = null;
            ImageBrush imageBrush;
            SpVoice speech = new SpVoice();
            IndexViewModel viewModel;
            System.Drawing.Image image;
            IntPtr icdev = IntPtr.Zero;

            InputWindow carInputWindow = null;
            KeyBoardWindow inputWindow = null;
            private Action<int, String> callbackAction;

            int st;
       
            public void MMPage_Loaded(object sender, RoutedEventArgs e)
            {
                this.KeyDown += MMPage_KeyDown;
                if (!"销售业务".Equals(billModel.Type))
                {
                    billModel.OuterSkinWeight = "";
                    billModel.OuterGrossWeight = "";
                    //txtWaiPi.Visibility = Visibility.Visible;
                    // wpBorder.Visibility = Visibility.Visible;
                    //txtWaiMao.Visibility = Visibility.Visible;
                    //wmBorder.Visibility = Visibility.Visible;
                }
                //读取IC卡

            }

            private void TextBox_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
            {
                string index = (string)((System.Windows.Controls.TextBlock)sender).Tag;
                int v = int.Parse(index);

                _syncContext.Post(showInputWindow, v);

            }

            private void showInputWindow(object obj)
            {
                int index = (int)obj;
                viewModel.index = index;
                if (index == 1 || index == 2)
                {
                    if (carInputWindow != null)
                    {
                        carInputWindow.Hide();
                    }

                    if (inputWindow == null)
                    {
                        inputWindow = new KeyBoardWindow(callbackAction);
                        inputWindow.Owner = mainWindow;
                        inputWindow.Width = mainWindow.Width;
                        inputWindow.Left = mainWindow.Left;
                        inputWindow.Top = SystemParameters.PrimaryScreenHeight - inputWindow.Height;
                    }
                    inputWindow.maxLength = 7;
                    inputWindow.getFlag("2");

                    if (index == 2)
                    {
                        inputWindow.viewModel.carNoArray.Clear();
                        foreach (String v in viewModel.waiPiWeighArray)
                        {
                            if (v != "")
                            {
                                inputWindow.viewModel.carNoArray.Add(v);
                            }

                        }
                    }
                    else if (index == 1)
                    {
                        inputWindow.viewModel.carNoArray.Clear();
                        foreach (String v in viewModel.waiMaoWeighArray)
                        {
                            if (v != "")
                            {
                                inputWindow.viewModel.carNoArray.Add(v);
                            }

                        }
                    }
                    inputWindow.showKeys(3);
                    inputWindow.Show();
                }
                else if (index == 3)
                {
                    if (inputWindow != null)
                    {
                        inputWindow.Hide();
                    }
                    if (carInputWindow == null)
                    {
                        carInputWindow = new InputWindow(callbackAction);
                        carInputWindow.Owner = mainWindow;
                        carInputWindow.Width = mainWindow.Width;
                        carInputWindow.Left = mainWindow.Left;
                        carInputWindow.Top = SystemParameters.PrimaryScreenHeight - carInputWindow.Height;
                    }
                    carInputWindow.maxLength = 7;
                    carInputWindow.viewModel.carNoArray.Clear();
                    foreach (String v in viewModel.carNoArray02)
                    {
                        if (v != "")
                        {
                            carInputWindow.viewModel.carNoArray.Add(v);
                        }

                    }

                    if (carInputWindow.viewModel.carNoArray.Count == 0)
                    {
                        carInputWindow.showKeys(1);
                    }
                    else
                    {
                        carInputWindow.showKeys(2);
                    }
                    carInputWindow.Show();
                }
                else
                {
                    if (inputWindow != null && inputWindow.IsActive)
                    {
                        inputWindow.Hide();
                    }
                    if (carInputWindow != null && carInputWindow.IsActive)
                    {
                        carInputWindow.Hide();
                    }
                }
            }


            private void CallBackExcute(int index, string val)
            {
                if (viewModel.index == 3)
                {
                    viewModel.carNoArray02[index] = val;
                    //BillModel.PiNumberList.Add(val);
                    //BillModel.PiNumberList[index] = val;
                    billModel.TrailerNumber = String.Join("", viewModel.carNoArray02);
                }

                if (viewModel.index == 1)
                {
                    viewModel.waiMaoWeighArray[index] = val;
                    //BillModel.PiNumberList.Add(val);
                    //BillModel.PiNumberList[index] = val;
                    string inputStr = String.Join("", viewModel.waiMaoWeighArray);
                    billModel.OuterGrossWeight = inputStr;

                }

                if (viewModel.index == 2)
                {
                    viewModel.waiPiWeighArray[index] = val;
                    //BillModel.PiNumberList.Add(val);
                    //BillModel.PiNumberList[index] = val;
                    string inputStr = String.Join("", viewModel.waiPiWeighArray);
                    billModel.OuterSkinWeight = inputStr;

                }
            }

            public Cards(BillModel billModel, MainWindow _win)
            {
                InitializeComponent();
                _syncContext = SynchronizationContext.Current;

                this.billModel = billModel;
                viewModel = new IndexViewModel();
                viewModel.index = 0;
                this.Loaded += new RoutedEventHandler(Sign_Loaded);

                this.DataContext = billModel;
                mainWindow = _win;
                this.Loaded += MMPage_Loaded;
                callbackAction += CallBackExcute;
                /*
                            if (billModel.TrailerNumber != null)
                            {
                                char[] charArray = billModel.TrailerNumber.ToCharArray();
                                for (int i = 0; i < billModel.TrailerNumber.Length; i++)
                                {
                                    viewModel.carNoArray02.Add(charArray[i].ToString());
                                }
                            }
                            else
                            {
                                for (int i = 0; i < 7; i++)
                                {
                                    viewModel.carNoArray02.Add("");
                                }
                            }*/

                if (billModel.TrailerNumber != null)
                {
                    char[] charArray = billModel.TrailerNumber.ToCharArray();

                    int len = billModel.TrailerNumber.Length;


                    if (len < 7)
                    {
                        for (int i = 0; i < billModel.TrailerNumber.Length; i++)
                        {
                            viewModel.carNoArray02.Add(charArray[i].ToString());
                        }

                        for (int i = 0; i < 7 - len; i++)
                        {
                            viewModel.carNoArray02.Add("");
                        }

                    }
                    else
                    {
                        for (int i = 0; i < 7; i++)
                        {
                            viewModel.carNoArray02.Add(charArray[i].ToString());
                        }
                    }

                }
                else
                {
                    for (int i = 0; i < 7; i++)
                    {
                        viewModel.carNoArray02.Add("");
                    }
                }
            }
            public void setPersonImage(ImageBrush image)
            {
                this.imageBrush = image;
                this.cardImagePanel.Background = image;
                //System.Drawing.Image bmp = image; // 自己初始化的有效的 image
                //System.IO.MemoryStream ms = new System.IO.MemoryStream();
                //System.Windows.Media.Imaging.BitmapImage bi = new System.Windows.Media.Imaging.BitmapImage();
                //bi.BeginInit();
                //bi.StreamSource = new MemoryStream(ms.ToArray()); // 不要直接使用 ms
                //bi.EndInit();
                //cardImage.Source = bi; // done!
                //ms.Close();

                //System.Drawing.Image bmp = image; // 自己初始化的有效的 image
                //System.Windows.Media.Imaging.BitmapSource bi =
                //System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                //bmp.GetHbitmap(),
                //IntPtr.Zero,
                //Int32Rect.Empty,
                //BitmapSizeOptions.FromEmptyOptions());
                // 上面以 bmp 格式为例的,其他格式自处理
                //this.cardImage.Source = bi; // Done!
                //this.image = image;
                //this.cardImage.Source= BitmapFrame.Create(image, BitmapCreateOptions.None, BitmapCacheOption.Default);;
            }
            private void Sign_Loaded(object sender, RoutedEventArgs e)
            {
                //MessageBox.Show(cardInfo.CardNo);
                //System.IO.MemoryStream objMSPhoto = new System.IO.MemoryStream(cardInfo.ArrPhotoByte, 0, cardInfo.ArrPhotoByte.Length);

                //ImageBrush imageBrush = new ImageBrush();
                //ImageSourceConverter imageSourceConverter = new ImageSourceConverter();
                //imageBrush.ImageSource = (ImageSource)imageSourceConverter.ConvertFrom(objMSPhoto);

                //this.cardImagePanel.Background = imageBrush;

                //MessageBox.Show(billModel.CarNo);
            }
            private void goIndex(object sender, RoutedEventArgs e)
            {
                Index index = new Index(mainWindow);
                mainWindow.BreakSpeak();
                CardDeviceUtil.ReceiveCard();
                NavigationService.GetNavigationService(this).Navigate(index);

                //NavigationService.GetNavigationService(this).Navigate(new Uri("/Pages/Index.xaml", UriKind.Relative));
            }

            private void showMessage(String message)
            {
                InfoWindow infoWindow = new InfoWindow(message);
                infoWindow.Owner = mainWindow;
                infoWindow.ShowDialog();
            }
        private void returnn(object sender, RoutedEventArgs e)//返回
        {
            this.NavigationService.GoBack();
        }
        private Nullable<double> getZhong(String type)
            {
                try
                {
                    if ("waiPi".Equals(type))
                    {
                        return 0.0;// billModel.OuterSkinWeight;
                    }
                    else if ("waiMao".Equals(type))
                    {
                        return 0.0;// billModel.OuterGrossWeight;
                    }
                    else
                    {
                        return 0.0;
                    }
                }
                catch
                {
                    return 0.0;
                }
            }
            private void doMakeCard(object sender, RoutedEventArgs e)
            {

                mainWindow.BreakSpeak();
            String ifstatement = App.getConfig().IfStatement;
            if (ifstatement.Equals("0"))
            {
                bool flag = click_statement();
                if (!flag)
                {
                    NavigationService.GetNavigationService(this).GoBack();
                    return;
                }
            }


            /*     if (billModel.TrailerNumber == null || billModel.TrailerNumber == "")
                 {
                     showMessage("请填写挂车车牌号");
                     return;
                 }*/

            //HttpPostWindow httpPostWindow = new HttpPostWindow();
            //httpPostWindow.Owner = mainWindow;
            //JObject paramJSON = new JObject();
            //paramJSON.Add("id", billModel.Id);
            //paramJSON.Add("facId", billModel.FacId);
            //JObject paramJSON2 = new JObject();
            //paramJSON2.Add("x", "116.83");
            //paramJSON2.Add("y", "30.06");
            //paramJSON.Add("reportPosition",paramJSON2);

            //httpPostWindow.setParamObject(paramJSON);

            //httpPostWindow.setOperation(HttpPostWindow.OperationType.doReport.ToString());
            //bool result = (bool)httpPostWindow.ShowDialog();
            //if (!result)
            //{
            //    string message = httpPostWindow.getMessage();
            //    if (null == message || "".Equals(message))
            //    {
            //        message = "签到失败,请联系管理员";
            //    }
            //    mainWindow.Speak("签到失败，请联系客服人工处理");
            //    showMessage(message);
            //    NavigationService.GetNavigationService(this).GoBack();
            //    return;
            //}


            //mainWindow.Speak("签到成功");
            String url = "http://" + App.getConfig().HttpServerIp + ":" + App.getConfig().HttpServerPort + "/guns/sysFileInfo/upload2";
                JObject json = new JObject();
                json.Add("id", billModel.Id);
                json.Add("driverCard", billModel.DriverCard);
               // json.Add("trailerNumber", billModel.TrailerNumber);挂车号
                HttpPostWindow httpPostWindow1 = new HttpPostWindow();
                httpPostWindow1.Owner = mainWindow;
                httpPostWindow1.setParamObject(json);

                httpPostWindow1.setOperation(HttpPostWindow.OperationType.uploadMakeCardResults.ToString());
                bool result1 = (bool)httpPostWindow1.ShowDialog();
                if (!result1)
                {
                    string message = httpPostWindow1.getMessage();
                    if (null == message || "".Equals(message))
                    {
                        message = "车辆报到失败,请联系工作人员处理";
                    }
                    mainWindow.Speak(message);
                    showMessage(message);
                    //CardDeviceUtil.ReceiveCard();
                    Index index1 = new Index(mainWindow);

                    NavigationService.GetNavigationService(this).Navigate(index1);
                    return;
                }
                  string  loadpLaceName= httpPostWindow1.LoadpLaceName();



            mainWindow.Speak("车辆报到完成," + loadpLaceName);
            showMessage("车辆报到完成,"+ loadpLaceName);
                


            Index index = new Index(mainWindow);

                NavigationService.GetNavigationService(this).Navigate(index);

            }

            private int checkCard(JObject paramObj)
            {
                ReadCardWindow readcardWindow = new ReadCardWindow();

                bool result = (bool)readcardWindow.ShowDialog();
                if (!result)
                {
                    return -1;
                }
                String guidCode = paramObj["guidCode"].ToString();
                if (!guidCode.Equals(readcardWindow.billModel.FacId))
                {
                    return -2;
                }
                String carNum = paramObj["carNumber"].ToString();
                if (!carNum.Equals(readcardWindow.billModel.CarNumber))
                {
                    return -3;
                }
                String control = paramObj["control"].ToString();
                if (!control.Equals(readcardWindow.billModel.ProdCode))
                {
                    return -4;
                }
                String billCode = paramObj["billCode"].ToString();
                if (!billCode.Equals(readcardWindow.billModel.Code))
                {
                    return -5;
                }
                String ynum = paramObj["ynum"].ToString();
                if (!ynum.Equals(readcardWindow.planNum))
                {
                    return -6;
                }

                return 1;
            }

            private void MakeCardSucces()
            {
                showMessage("制卡成功,请取卡");
                CardDeviceUtil.PopupCard();
                Reader.hc_exit(icdev);


            }
            private void MakeCardError()
            {
                showMessage("制卡失败,请联系管理员");
            }


            private void doInput(object sender, RoutedEventArgs e)
            {
                String val = ((Button)sender).Content.ToString();

                inputText(val);
            }
            private void inputText(String val)
            {
                //    String value = "";
                //    if (curInputTag == "wp")
                //    {
                //        value = this.wpText.Text;
                //    }
                //    else if (curInputTag == "wm")
                //    {
                //        value = this.wmText.Text;
                //    }
                //    else if (curInputTag == "mobile")
                //    {
                //        value = this.mobileText.Text;
                //    }

                //    String value2 = "";
                //    if ("-1".Equals(val))
                //    {
                //        if (value.Length > 0)
                //        {
                //            value2 = value.Substring(0, value.Length-1);
                //        }
                //    }
                //    else
                //    {
                //        value2 = getNumField(value, val);
                //    }

                //    if (curInputTag == "wp")
                //    {
                //        this.wpText.Text = value2;
                //    }
                //    else if (curInputTag == "wm")
                //    {
                //        this.wmText.Text = value2;
                //    }
                //    else if (curInputTag == "mobile")
                //    {
                //        this.mobileText.Text = value2;
                //    }
            }
            private String getNumField(String val, String inputVal)
            {
                if (inputVal == "消除")
                {
                    return "";
                }
                if (inputVal == "." && curInputTag == "mobile")
                {
                    return val;
                }
                if (inputVal == "." && "".Equals(val))
                {
                    return val;
                }
                if (inputVal == "." && val.IndexOf(".") >= 0)
                {
                    return val;
                }

                if (curInputTag == "mobile" && val.Length >= 11)
                {
                    return val;
                }

                if ((curInputTag == "wp" || curInputTag == "wm") && val.IndexOf(".") >= 0)
                {
                    if (val.IndexOf(".") + 3 == val.Length) return val;
                }
                if ((curInputTag == "wp" || curInputTag == "wm") && !"".Equals(val))
                {
                    if (double.Parse(val + inputVal) > 99.99) return val;
                }

                String value = val;

                value = val + inputVal;

                return value;
            }

            public void MMPage_KeyDown(object sender, KeyEventArgs e)
            {
                string val = getKeyValue(e.Key);
                if ("back".Equals(val))
                {
                    inputText("-1");
                }
                else if ("point".Equals(val))
                {
                    inputText(".");
                }
                else
                {
                    if (e.Key.ToString().StartsWith("D"))
                    {
                        inputText(val);
                    }
                }
                //MessageBox.Show(e.Key.ToString());
                e.Handled = true;
            }

            private string getKeyValue(Key key)
            {
                string KeyValue = "-1";

                switch (key)
                {
                    case Key.D1:
                        KeyValue = "1";
                        break;
                    case Key.D2:
                        KeyValue = "2";
                        break;
                    case Key.D3:
                        KeyValue = "3";
                        break;
                    case Key.D4:
                        KeyValue = "4";
                        break;
                    case Key.D5:
                        KeyValue = "5";
                        break;
                    case Key.D6:
                        KeyValue = "6";
                        break;
                    case Key.D7:
                        KeyValue = "7";
                        break;
                    case Key.D8:
                        KeyValue = "8";
                        break;
                    case Key.D9:
                        KeyValue = "9";
                        break;
                    case Key.D0:
                        KeyValue = "0";
                        break;
                    case Key.OemPeriod:
                        KeyValue = "point";
                        break;
                    case Key.Back:
                        KeyValue = "back";
                        break;
                    case Key.Enter:
                        KeyValue = "enter";
                        break;
                }
                return KeyValue;
            }
            private bool click_statement()
            {
                StatementWindow statementWindow = new StatementWindow();
                statementWindow.setPersonImage(this.imageBrush);
                statementWindow.setBillModel(this.billModel);
            Grid layer = new Grid() { Background = new SolidColorBrush(System.Windows.Media.Color.FromArgb(200, 0, 0, 0)) };
                UIElement original = mainWindow.Content as UIElement;//MainWindows父窗体
                mainWindow.Content = null;
                //容器Grid
                Grid container = new Grid();
                container.Children.Add(original);//放入原来的内容
                container.Children.Add(layer);//在上面放一层蒙板
                                              //将装有原来内容和蒙板的容器赋给父级窗体
                mainWindow.Content = container;
                statementWindow.Owner = mainWindow;
                bool result = (bool)statementWindow.ShowDialog();
                return result;
            }

            public void UploadImage(string uploadUrl, string imgPath, long id, string fileparameter = "file")
            {
                try
                {
                    HttpWebRequest request = WebRequest.Create(uploadUrl) as HttpWebRequest;
                    request.AllowAutoRedirect = true;
                    request.Method = "POST";
                    request.ServicePoint.Expect100Continue = false;

                    string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
                    request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
                    byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
                    byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

                    int pos = imgPath.LastIndexOf("/");
                    string fileName = imgPath.Substring(pos + 1);

                    //请求头部信息
                    StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"" + fileparameter + "\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));
                    byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());

                    FileStream fs = new FileStream(imgPath, FileMode.Open, FileAccess.Read);
                    byte[] bArr = new byte[fs.Length];
                    fs.Read(bArr, 0, bArr.Length);
                    fs.Close();

                    Stream postStream = request.GetRequestStream();
                    postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
                    postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
                    postStream.Write(bArr, 0, bArr.Length);
                    postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
                    postStream.Close();

                    HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                    Stream instream = response.GetResponseStream();
                    StreamReader sr = new StreamReader(instream, Encoding.UTF8);
                    string content = sr.ReadToEnd();
                    JObject rspJson = JObject.Parse(content);
                    string code = rspJson["code"].ToString();
                    if (code.Equals("00000"))
                    {
                        JObject data = (JObject)rspJson.GetValue("data");
                        String filaName = (String)data.GetValue("fileObjectName");
                        doUpdateScreenPicture(filaName, id);
                    }
                }
                catch (Exception ex) { }

            }
            private void doUpdateScreenPicture(String imagePath, long id)
            {
                JObject paramObject = new JObject();
                paramObject.Add("imagePath", imagePath);
                paramObject.Add("id", id);

                try
                {
                    String serverIp = App.getConfig().HttpServerIp;
                    String serverPort = App.getConfig().HttpServerPort;
                    String response = HttpPostHelper.doHttpPost("http://" + serverIp + ":" + serverPort + "/qd-s-factory/clientApi/updateBillCardPicture", paramObject.ToString());
                    JObject rspJson = JObject.Parse(response);

                }
                catch (Exception ex) { }
            }


        }
    }


